package Test.ThreadLocalDemo;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;

/**
 * @author handsomePot
 * @date 2022/1/13 22:48
 */
public class Demo01 {

    private static final AtomicLong al = new AtomicLong();

    private static final ThreadLocal<Long> local = new ThreadLocal<Long>() {
        @Override
        protected Long initialValue() {
            return al.getAndIncrement();
        }
    };

    public static Long get() {
        return local.get();
    }


    public static class Task implements Runnable {
        @Override
        public void run() {
            try {
                System.out.println("当前线程是:" + Thread.currentThread().getName() +
                        " ; 分配的id为：" + get());
            } finally {
                local.remove();
            }
        }
    }


    public static void main(String[] args) {
        Task task = new Task();

        new Thread(task, "关羽").start();

        new Thread(task, "张飞").start();

        new Thread(task, "刘备").start();

    }

}
